<template>
  <div class="address-order">
    <van-contact-card
      ref="config"
      :type="currentContact.name?'edit':'add'"
      add-text="添加收货地址"
      :name="currentContact.name"
      :tel="currentContact.tel"
      v-comeIn="currentContact"
      @click="showList = true"
    ></van-contact-card>
    <!-- 联系人列表 -->
    <van-popup v-model="showList" position="bottom">
      <AddressTemp></AddressTemp>
    </van-popup>
  </div>
</template>

<script>
import AddressTemp from "@/components/user/children/AddressTemp";
import { getAddressList } from "@/request/api.js";
export default {
  components: {
    AddressTemp
  },
  data() {
    return {
      chosenContactId: null,
      editingContact: {},
      showList: false,
      showEdit: false,
      isEdit: false,
      list: [
        {
          name: "张三",
          tel: "13000000000",
          address: "广东省",
          id: 0
        }
      ]
    };
  },
  directives: {
    comeIn: {
      update(el, binding, vnode) {
        if ( binding.oldValue.id !== binding.value.id && binding.value.id) {
          if(el.children[1].children[2]){
            el.children[1].children[2].innerHTML =
              "收货地址:" + binding.value.address;
            
          }else {
            let div1 = document.createElement("div");
            div1.innerHTML = "收货地址:" + binding.value.address;
            el.children[1].appendChild(div1);

          }
          vnode.context.showList = false;
        }
      }
    }
  },

  computed: {
    currentContact() {

      return this.$store.state.curAddress;
    }
  },

  methods: {
    // 添加联系人
    onAdd() {
      this.editingContact = { id: this.list.length };
      this.isEdit = false;
      this.showEdit = true;
    },

    // 编辑联系人
    onEdit(item) {
      this.isEdit = true;
      this.showEdit = true;
      this.editingContact = item;
    },

    // 保存联系人
    onSave(info) {
      this.showEdit = false;
      this.showList = false;

      if (this.isEdit) {
        this.list = this.list.map(item => (item.id === info.id ? info : item));
      } else {
        this.list.push(info);
      }
      this.chosenContactId = info.id;
    },

    // 删除联系人
    onDelete(info) {
      this.showEdit = false;
      this.list = this.list.filter(item => item.id !== info.id);
      if (this.chosenContactId === info.id) {
        this.chosenContactId = null;
      }
    }
  },
  mounted() {
    if (this.currentContact.address) {
      let dv = this.$refs.config;
      let div1 = document.createElement("div");
      div1.innerHTML = "收货地址:" + this.currentContact.address;
      dv.children[1].appendChild(div1);
    }
  },
  updated(){
    let dv = this.$refs.config;
    if(!this.$store.state.curAddress.id && dv.children[1].children.length > 0) {
      console.log(32)
      dv.children[1].removeChild(dv.children[1].children[0])
    }
  }
};
</script>

<style lang="less" scoped>
.van-popup--bottom {
  height: 75%;
}
</style>